package com.fengchao.util.wechat.commonality;

import java.io.StringReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fengchao.util.wechat.commonality.rendermodel.Article;
import com.fengchao.util.wechat.commonality.rendermodel.NewsRespMessage;
import com.fengchao.util.wechat.commonality.rendermodel.TextRespMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 处理微信消息的工具类（发送和接收消息）
 * @author xuri002
 *
 */
public class WeChatMessageUtil {
	
	  /**
     * 文本消息对象转换成xml 
     *  
     * @param
     * @return xml 
     */  
    public static String textMessageToXml(TextRespMessage textMessage) {
        xstream.alias("xml", TextRespMessage.class);  
        return xstream.toXML(textMessage);  
    }  
    /** 
     * 图文消息对象转换成xml 
     *  
     * @param newsRespMessage 图文消息对象
     * @return xml 
     */  
    public static String newsMessageToXml(NewsRespMessage newsRespMessage) {
        xstream.alias("xml", NewsRespMessage.class);  
        xstream.alias("item", Article.class);
        return xstream.toXML(newsRespMessage);  
    }  
    
	/**
	 * 把对象转化为一般的的XML不用 <![CDATA[]]>块包括内容
	 * @return
	 */
	public static <T> String generateSimpleXml(T t){
		XStream xstream=new XStream();
		xstream.alias("xml", t.getClass());//一级标签为xml
		 return xstream.toXML(t).replace("__", "_");
	}
    
    /** 
     * 解析微信发来的请求（XML） 
     *  
     * @return
     * @throws Exception 
     */  
    @SuppressWarnings("unchecked")  
    public static Map<String, String> parseXml( String xmlContent) throws Exception {  
        // 将解析结果存储在HashMap中  
        Map<String, String> map = new HashMap<String, String>();  
        // 从request中取得输入流  
        StringReader inputStream = new StringReader(xmlContent);  
        // 读取输入流  
        SAXReader reader = new SAXReader();  
        Document document = reader.read(inputStream);  
        // 得到xml根元素  
        Element root = document.getRootElement();  
        // 得到根元素的所有子节点  
        List<Element> elementList = root.elements();  
        // 遍历所有子节点  
        for (Element e : elementList)  
            map.put(e.getName(), e.getText());  
        // 释放资源  
        inputStream.close();  
        inputStream = null;  
        return map;  
    }  
    
    /** 
     * 扩展xstream，使其支持CDATA块 
     *  
     */
    private static XStream xstream = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记  
                boolean cdata = true;  
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);  
                }  
                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {  
                        writer.write("<![CDATA[");  
                        writer.write(text);  
                        writer.write("]]>");  
                    } else {  
                        writer.write(text);  
                    }  
                }  
            };  
        }  
    }); 
    
}
